import { ModalForm, ProFormText } from '@ant-design/pro-components';
import type { ProFormInstance, ModalFormProps } from '@ant-design/pro-components';
import { useRef, useState } from 'react';

interface IProps {
  actionType: 'add' | 'edit';
  onFinished: ModalFormProps['onFinish'];
  triggerEl: ModalFormProps['trigger'];
  editRoleInfo?: ROLE.RoleType;
}
const AddOrEditRoleModal: React.FC<IProps> = ({
  actionType,
  onFinished,
  triggerEl,
  editRoleInfo,
}) => {
  const [modalVisible, setModalVisible] = useState<boolean>(false);
  const formRef = useRef<ProFormInstance>();

  const setEditInfo = () => {
    if (editRoleInfo) {
      formRef.current?.setFieldsValue({
        roleName: editRoleInfo.name,
      });
    }
  };

  return (
    <ModalForm
      formRef={formRef}
      open={modalVisible}
      onOpenChange={setModalVisible}
      modalProps={{
        destroyOnClose: true,
        width: 520,
        forceRender: actionType === 'edit',
      }}
      title={actionType === 'add' ? '新增角色' : '编辑角色'}
      trigger={
        <div
          onClick={() => {
            setModalVisible(true);
            if (actionType === 'edit') setEditInfo();
          }}
        >
          {triggerEl}
        </div>
      }
      onFinish={onFinished}
    >
      <ProFormText
        name="roleName"
        label="角色名称"
        rules={[
          {
            required: true,
            message: '必填',
          },
        ]}
      />
    </ModalForm>
  );
};

export default AddOrEditRoleModal;
